package cn.glfs.domain.strategy.service.rule.tree.impl;

import cn.glfs.domain.strategy.model.entity.TreeActionEntity;
import cn.glfs.domain.strategy.model.valobj.LogicTreeAwardVO;
import cn.glfs.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.glfs.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import cn.glfs.domain.strategy.repository.IStrategyRepository;
import cn.glfs.domain.strategy.service.armory.IStrategyDispatch;
import cn.glfs.domain.strategy.service.rule.tree.ILogicTreeNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


/**
 * 库存扣减节点
 */
@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyDispatch strategyDispatch;
    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue) {
        log.info("规则过滤-库存扣减 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        Boolean status = strategyDispatch.subtractionAwardStock(strategyId, awardId);
        if (status) {
            log.info("规则过滤-库存扣减-成功 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);

            strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                            .strategyId(strategyId)
                            .awardId(awardId)
                            .build());

            return TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .treeAwardVO(LogicTreeAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue(ruleValue)
                            .build())
                    .build();
        }

        log.info("规则过滤-库存扣减-失败 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        return TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .build();
    }
}